<template>
  <div>
    <div class="page-wrapper">
      <div class="operation-btn-wrapper">
        <!-- <div class="operation-btn" @click="goBack">返回</div> -->
        <el-button @click="goBack">返回</el-button>
        <div class="operation-btn-space"></div>
        <el-button type="primary" @click="exportUsers">导出用户</el-button>
        <el-button @click="importUsers">导入用户</el-button>
        <!-- <div class="operation-btn" @click="checkoutAccount">切换登录</div> -->
      </div>
      <el-radio-group v-model="currentPlatform">
        <el-radio-button type="info" v-for="item in platformList" :label="item.code" :key="item.code">{{item.message}}</el-radio-button>
      </el-radio-group>
      <div class="group-btn-list">
        <el-button
          class="group-btn-item"
          @click="setGroupIndex(group.code)"
          :type="currentGroup === group.code ? 'info' : ''"
          v-for="(group) in allGroupList"
          :key="group.code"
          size="small"
        >
          {{group.alias}}
        </el-button>
      </div>
      <div class="account-wrapper">
        <div class="account-info">
          <div id="accountList" class="info-item">
          <el-tree
            size="medium"
            :data="accountList"
            highlight-current
            :props="defaultProps" @node-click="handleNodeClick">
            </el-tree>
          </div>
        </div>
        <div class="account-menu">
          <!-- <div class="account-name">当前账户：{{
            currentLoginAccount ? currentLoginAccount.name : '未登录' }}</div> -->
          <!-- <div class="account-btn" @click="addAccount">新加账户</div>
          <div class="account-btn" @click="addSub">添加子账户</div>
          <div class="account-btn" @click="updateAccount">修改账户</div>
          <div class="account-btn" @click="removeAccount">删除账户</div> -->
          <el-button class="menu-btn" type="info" @click="addAccount">新加账户</el-button>
          <el-button class="menu-btn" type="info" @click="addSub">添加子账户</el-button>
          <el-button class="menu-btn" type="info" @click="updateAccount">修改账户</el-button>
          <el-button class="menu-btn" type="info" @click="removeAccount">删除账户</el-button>
        </div>
      </div>
    </div>
    <el-dialog width="500px" title="账户管理" :visible.sync="dialogVisible">
      <el-form ref="elForm" :model="model" :rules="rules" label-position="left">
        <el-form-item v-if="currentSelect && currentSelect.name && modalType === 'sub'" label="已选父级：">
          <span>{{ currentSelect.name }}</span>
        </el-form-item>
        <el-form-item v-if="modalType !== 'sub' && model.level !== 9999" label="等级" prop="level">
          <el-select v-model="model.level" placeholder="必填项">
            <el-option v-for="(item,index) in levelList" :key="index" :label="item.message" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录名称" prop="name">
          <el-input v-model.trim="model.name" placeholder="必填项" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="psw">
          <el-input v-model.trim="model.psw" placeholder="必填项" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="modalType !== 'sub' && model.level !== 9999" label="分组" prop="group">
          <el-select v-model="model.group" placeholder="选填">
            <el-option v-for="(item,index) in groupList" :key="index" :label="item.alias" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安全码" prop="code" key="code">
          <el-input v-model.trim="model.code" placeholder="选填" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort" key="sort">
          <el-input v-model="model.sort" type="number" placeholder="数值越大，排序越前" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="goModelValidate"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccountList, setAccountList, levelList, platformList, getAccountListAll, setAccountListAll } from '../common'
import { getGroupListByPlatform } from '@/views/Group/group-help'

export default {
  data () {
    return {
      platformList,
      groupList: [],
      allGroupList: [],
      currentGroup: -2,
      currentPlatform: 1,
      dialogVisible: false,
      model: {},
      levelList: levelList,
      rules: {
        level: [{ required: true, message: '不能为空' }],
        name: [{ required: true, message: '不能为空' }],
        psw: [{ required: true, message: '不能为空' }]
      },
      currentSelect: null,
      accountList: [],
      defaultProps: {
        label: (data, node) => {
          const { name, level } = data
          // eslint-disable-next-line no-unused-vars
          const levelMeg = (levelList.find(e => e.code === level) || {}).message
          // const levelMeg = level === 1 ? '等级一' : level === 2 ? '等级二' : '等级三'
          // return name + `--[${levelMeg}]`
          return name
        }
      },
      modalType: 'add' // add, edit, sub
    }
  },
  computed: {
    currentLoginAccount () {
      return this.$store.state.currentLoginAccount
    },
    platform () {
      return this.$route.query.platform || ''
    }
  },
  created () {
    // this.accountList = [...getAccountList()]
    this.getAccountListByPlatform()
    this.getGroupList()
    this.getFilterGroupList()
    this.resetModel()
  },

  watch: {
    platform: {
      immediate: true,
      handler (val) {
        if (val) {
          this.currentPlatform = val
          this.model = {}
        }
      }
    },
    currentPlatform () {
      this.currentSelect = null
      this.getAccountListByPlatform()
      this.getGroupList()
      this.getFilterGroupList()
    },
    modalType (val) {
      if (val === 'sub') {
        this.$set(this.rules, 'psw', [{ required: false }])
      } else {
        this.$set(this.rules, 'psw', [{ required: true, message: '不能为空' }])
      }
    },
    'model.level' (val) {
      if (val && val === 9999) {
        this.$set(this.rules, 'psw', [{ required: false }])
      }
    }
  },

  methods: {
    merge (source, newSource) {
      // eslint-disable-next-line no-unreachable
      const result = {}
      for (let i = 0; i < platformList.length; i++) {
        const { code } = platformList[i]
        const platformUserList = source[code] || []
        const platformUserNewList = newSource[code] || []
        const list = [...platformUserList, ...platformUserNewList]
        const newList = []
        list.forEach(item => {
          const index = newList.findIndex(e => {
            return e.name === item.name
          })
          if (index > -1) {
            newList.splice(index, 1, item)
          } else {
            newList.push(item)
          }
        })
        result[code] = newList
      }
      // eslint-disable-next-line no-unreachable
      console.log('merge result: ', result)
      return result
    },
    exportUsers () {
      const all = getAccountListAll() || {}
      const result = {}
      let txt = ''
      Object.keys(all).forEach(key => {
        const value = all[key]
        const keyName = (platformList.find(item => String(item.code) === String(key)) || {}).message
        result[keyName] = value
      })
      txt = JSON.stringify(result, null, 2)
      console.log(txt)
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('write-file', { fileName: '用户表记录', fileContent: txt })
    },
    importUsers () {
      console.log('import users')
      const input = document.createElement('input')
      input.type = 'file'
      input.style.display = 'none'
      document.body.appendChild(input)
      input.onchange = (e) => {
        const reader = new FileReader()
        reader.onload = () => {
          const result = reader.result
          if (result) {
            console.log(result)
            const newUsers = JSON.parse(result)
            const importResult = {}
            Object.keys(newUsers).forEach(key => {
              const keyCode = (platformList.find(item => String(item.message) === String(key)) || {}).code
              if (keyCode || keyCode === 0) {
                importResult[keyCode] = newUsers[key]
              }
            })
            console.log('importResult: ', importResult)
            try {
              const newUserList = this.merge(getAccountListAll(), importResult)
              setAccountListAll(newUserList)
              this.$message.success('导入成功')
              this.getAccountListByPlatform()
            } catch (error) {
              console.log(error)
              this.$message.error('导入失败')
            }
          }
        }
        reader.readAsText(e.target.files[0])
        setTimeout(() => {
          document.body.removeChild(input)
        }, 500)
      }
      input.click()
    },
    setGroupIndex (code) {
      this.currentGroup = code
      const list = getAccountList(this.currentPlatform)
      // 所有
      if (code === -2) {
        this.accountList = list
        return
      }
      // 未分组
      if (code === -1) {
        this.accountList = list.filter(e => !e.group || e.group === -1)
        return
      }
      this.accountList = list.filter(e => {
        return Number(e.group) === Number(code)
      })
    },
    getFilterGroupList () {
      const index = this.currentPlatform
      this.currentGroup = -2
      this.allGroupList = (getGroupListByPlatform(index) || [])
    },
    getGroupList () {
      const index = this.currentPlatform
      this.groupList = (getGroupListByPlatform(index) || []).filter(e => ![-1, -2].includes(e.code))
    },
    findOne (regionData, id) {
      if (!regionData || !regionData.length) {
        return null
      }
      for (let i = 0; i < regionData.length; i++) {
        const child = regionData[i]
        if (child.id === id) {
          return child
        }
        const data = this.findOne(child.children, id)
        if (data) {
          return data
        }
      }
      return null
    },
    // 根据当前的平台查找账户列表
    getAccountListByPlatform (platform = this.currentPlatform) {
      const data = getAccountList(platform)
      console.log('data !!! === ')
      console.log(data)
      this.accountList = data
      return data
    },
    handleNodeClick (d) {
      console.log('node click')
      console.log(d)
      this.resetModel()
      this.currentSelect = null
      this.currentSelect = { ...d }
    },
    resetModel () {
      this.model = {
        sort: 0,
        level: 1
      }
      this.$refs.elForm && this.$refs.elForm.resetFields()
    },
    goModelValidate () {
      this.$refs.elForm.validate((isValid) => {
        if (!isValid) return
        const list = this.getAccountListByPlatform()
        if (this.modalType === 'add') {
          const item = { ...this.model }
          item.id = Date.now()
          list.push(item)
        } else if (this.modalType === 'edit') {
          const item = this.findOne(list, this.model.id)
          if (item) {
            const { level, name, psw, code, sort, group } = this.model
            item.level = level
            item.name = name
            item.psw = psw
            item.code = code
            item.sort = sort
            item.group = group
          } else {
            console.error('没有找到对应数据！')
          }
        } else if (this.modalType === 'sub') {
          const item = this.findOne(list, this.parentId)
          if (item) {
            if (!item.children) {
              item.children = []
            }
            const data = { ...this.model }
            data.id = Date.now()
            data.level = 9999
            item.children.push(data)
          }
        }
        console.log('set account list: ', this.currentPlatform, list)
        setAccountList(this.currentPlatform, list)
        this.dialogVisible = false
        this.currentSelect = null
        this.$refs.elForm.resetFields()
        this.$nextTick(() => {
          this.resetModel()
          this.getAccountListByPlatform()
        })
      })
    },
    addAccount () {
      this.dialogVisible = true
      this.resetModel()
      this.modalType = 'add'
    },
    addSub () {
      if (!this.currentSelect || !this.currentSelect.id) {
        return this.$message.error('请选择一个父级')
      }
      this.modalType = 'sub'
      this.parentId = this.currentSelect.id
      this.dialogVisible = true
    },
    updateAccount () {
      if (!this.currentSelect || !this.currentSelect.id) {
        return this.$message.error('请选择修改的账户')
      }
      this.dialogVisible = true
      this.model = { ...this.currentSelect }
      this.modalType = 'edit'
    },
    removeAccount () {
      if (!this.currentSelect || !this.currentSelect.id) {
        return this.$message.error('请选择删除的数据')
      }
      this.$confirm('是否继续选中的账户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // const list = this.getAccountList()
        this.getAccountListByPlatform()
        const list = [...this.accountList]
        this._remove(list, this.currentSelect.id)
        this.currentSelect = null
        setAccountList(this.currentPlatform, list)
        this.$nextTick(() => {
          this.getAccountListByPlatform()
          // this.accountList = this.getAccountList()
        })
      })
    },
    _remove (list, id) {
      if (!list || !list.length) {
        return null
      }
      for (let i = 0; i < list.length; i++) {
        const child = list[i]
        if (child.id === id) {
          list.splice(i, 1)
          return
        }
        this._remove(child.children, id)
      }
      return null
    },
    goBack () {
      this.$router.push({
        name: 'Home'
      })
    },
    checkoutAccount () {
      if (!this.currentSelect) {
        return this.$message.error('请先选中切换的账户')
      }
      // this.currentLoginAccount = { ...this.currentSelect }
      this.$message.success(`切换成功，你好[${this.currentSelect.name}]`)
      this.$store.commit('setCurrentLoginAccount', this.currentSelect)
      // setCurrentLogin(this.currentLoginAccount)
      this.loginName = this.currentSelect.name
    }
  }
}
</script>

<style>
body, html {
  background-color: #f2f2f2;
}
</style>

<style lang="stylus" scoped>
.group-btn-list {
  display: flex;
  flex-wrap: wrap;
  margin: 10px 0;
  .group-btn-item {
    margin-right: 4px;
    margin-left: 0;
    margin-bottom: 6px;
  }
}

.model-item {
  display: flex;
  .el-form-item__content {
    flex: 1;
  }
}

>>> .is-current > .el-tree-node__content {
  background-color: #a6c9f1 !important;
  color: #fff;

  .el-tree-node__expand-icon {
    color: #fff;

    &.is-leaf {
      color: transparent;
    }
  }
}

.page-wrapper {
  padding: 10px 20px;
}

.operation-btn-wrapper {
  display: flex;
  padding: 15px 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #ddd;
}

.operation-btn {
  font-size: 13px;
  padding: 6px 20px;
  margin-right: 4px;
  background-color: #777;
  color: #f2f2f2;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  margin-bottom: 8px;
}

.operation-btn-space {
  flex: 1;
}

.operation-btn:last-child {
  margin-right: 0;
}

.account-wrapper {
  display: flex;
  padding: 10px 0;
  box-sizing: border-box;
}

.account-info {
  flex: 1;
  display: flex;
  padding-right: 20px;
  flex-direction: column;
}

.info-item {
  display: flex;
  flex-direction: column;
  font-size: 14px;
  margin-bottom: 10px;
}

.info-item .value {
  display: inline-block;
  padding: 4px;
  cursor: pointer;
}

.info-item .value.active {
  background-color: #999;
  color: #fff;
}

.info-item .label {
  min-width: 80px;
}

.account-menu {
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .menu-btn {
    min-width: 160px;
    width: 100%;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }
}

.account-menu .account-name {
  font-weight: 400;
  margin-bottom: 20px;
}

.account-menu .account-btn {
  font-size: 14px;
  padding: 6px 0;
  margin-right: 4px;
  background-color: #777;
  color: #f2f2f2;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  margin-bottom: 8px;
}
</style>
